<?php

Yii::import('application.models._base.BaseUser');

class User extends BaseUser
{
    public $repassword;
    public $login_username;

	public static function model($className=__CLASS__) {
		return parent::model($className);
	}
    public function rules()
    {
        return array(
            array('username','checkName','on'=>'create'),//用户名已存在 -8
            array('username','checkUSName','on'=>'update'),
            array('email','checkEmail','on'=>'create'),//邮箱已存在 -10
            array('username', 'required','message'=>'-1','on'=>'create'),//用户名必须填写
//            array('username','match','pattern'=>'/^[^@]{2,20}$/i','message'=>'-2','on'=>'create'),
            array('username','match','pattern'=>'/^[\w]{2,20}$/i','message'=>'-2','on'=>'create,update'),
            //判断登录用户名是否是邮箱
            array('password', 'required','message'=>'-4','on'=>'create'),//密码必须填写
            array('password', 'length', 'max'=>30,'tooLong'=>'-5','on'=>'create'),//密码不得大于30个字符
            array('password', 'length', 'min'=>2,'tooShort'=>'-6','on'=>'create'),//密码不得小于2个字符
            array('repassword','compare','compareAttribute'=>'password','message'=>'-7','on'=>'create'),//两次密码必须一致
            array('email', 'required','message'=>'-9','on'=>'create'),//邮箱必须填写
            array('email','email','message'=>'-11','on'=>'create'),//邮箱格式不正确
            array('email', 'length', 'max'=>50,'tooLong'=>'-12','on'=>'create'),//邮箱不得大于50个字符


            array('phone,level,province,fingerprint,group_id,recommend,recommend_time,role_salt,total_shares, total_forward,total_favorite_album,total_favorite_share,total_albums,total_follows,total_followers,create_time,domain,is_domain,update_username,sex,nick_name,avatar_public,feeling,bg,info_status, email_token, email_token_exptime,last_login_time,last_login_ip,role,loginnum,salt,repid,reg_type,avatar_status', 'safe'),
            array('phone,level,province,fingerprint,group_id,recommend,recommend_time,role_salt,total_shares, total_forward,total_favorite_album,total_favorite_share,total_albums,total_follows,total_followers,id, username,domain,is_domain,nick_name,avatar_public,feeling,bg,info_status, email_token, email_token_exptime,last_login_time,last_login_ip,role,loginnum, status, password, email,reg_type, create_time,salt,repid,avatar_status', 'safe', 'on'=>'search'),
        );
    }
    public function beforeSave(){
        //如果是新增
        if($this->isNewRecord){
            $this->create_time = time();
            $this->salt = Xtutuquan::randStr(6);
            $this->regip = Xtutuquan::getClientIP();
            $this->password = sha1($this->password.$this->salt);
            $this->email_token = md5($this->username.$this->password.$this->create_time);
            $this->email_token_exptime = time()+60*60*24;//过期时间为24小时后
        }
        return true;
    }


    /**
     * 注册账号
     */
    public function register($username,$password,$repassword,$email,$nick_name){
        $User = new User();
        $User->setScenario('create');
        $username = CHtml::encode($username);
        $password = CHtml::encode($password);
        $repassword = CHtml::encode($repassword);
        $email = CHtml::encode($email);
        $nick_name = CHtml::encode($nick_name);
        $data = array(
            'username'=>$username,
            'password'=>$password,
            'email' => $email,
            'repassword'=>$repassword,
            'nick_name'=>$nick_name,
            'group_id'=>Yii::app()->params['regGroupId'],
        );
        $User->setAttributes($data);
        if($User->save()){
            $id = $User->attributes['id'];
            $str = $email.'|'.$id;
            $str = Xtutuquan::encryption($str);
            Xtutuquan::_cookiesSet('email',$str,time()+3600);
            //发送邮件
            //1：获取系统邮件发送配置文件信息
            $v = Xtutuquan::getEmailConfig();
            $title = $v['emailRegisterTitle'];
            $content = $v['emailRegisterContent'];
            $content = str_replace('{{username}}',$nick_name,$content);
            $content = str_replace('{{webname}}',Yii::app()->params['webName'],$content);
            $weburl = Yii::app()->request->hostInfo.Yii::app()->createUrl('auth/activation',array('confirmation'=>$User->email_token));
            $content = str_replace('{{weburl}}',$weburl,$content);
            Xtutuquan::_sendEmail($email,$title,$content);
            return '1';
        }else{
            return $User->getErrors();
        }
    }



    /**
     * 验证字段
     */
    public function checkField($field,$type){
        $this->setScenario('create');
        $data = array();
        switch($type){
            case 'username' :
                $data['username'] = $field;
                break;
            case 'email':
                $data['email'] = $field;
                break;
            default:
                return 0;
        }
        $this->setAttributes($data);
        $this->save($data);
        $error = $this->getErrors();
        switch($error[$type][0]){
            case '-8' :
                return -1;
                break;
            case '-10':
                return -1;
                break;
            default:
                return 1;
        }
    }

    public function checkName($attribute,$params){
        $info = $this->findByAttributes(array('username'=>$this->username,'status'=>1));
        if($info){
            $this->addError($attribute,'-8');
        }
    }
    public function checkEmail($attribute,$params){
        $info = $this->findByAttributes(array('email'=>$this->email,'status'=>1));
        if($info){
            $this->addError($attribute,'-10');
        }
    }
    public function checkUSName($attribute,$params){
        $uinfo = User::model()->findByPk($this->id);
        $info = $this->findByAttributes(array('username'=>$this->username));
        if($this->username != $uinfo->username && $this->username ){
            if($info){
                $this->addError($attribute,'-19');
            }
        }
    }
    public function checkUName($field,$uid = 0){
        if($uid){
            $uinfo = User::model()->findByPk($uid);
            if($uinfo->username == $field){
                return 1;
            }else{
                $info = $this->findByAttributes(array('username'=>$field));
                if($info){
                    return -1;
                }else{
                    return 1;
                }
            }
        }else{
            $info = $this->findByAttributes(array('username'=>$field));
            if($info){
                return -1;
            }else{
                return 1;
            }
        }
    }
    public function checkDomain($field,$uid = 0){
        if($uid){
            $uinfo = User::model()->findByPk($uid);
            if($uinfo->domain == $field){//相同
                return 1;
            }else{
                $info = $this->findByAttributes(array('domain'=>$field));
                if($info){
                    return -1;
                }else{
                    return 1;
                }
            }
        }else{
            $info = $this->findByAttributes(array('domain'=>$field));
            if($info){
                return -1;
            }else{
                return 1;
            }
        }
    }
    public function checkNickName($field,$uid = 0){
        if($uid){
            $uinfo = User::model()->findByPk($uid);
            if($uinfo->nick_name == $field){
                return 1;
            }else{
                $info = $this->findByAttributes(array('nick_name'=>$field));
                if($info){
                    return -1;
                }else{
                    return 1;
                }
            }
        }else{
            $info = $this->findByAttributes(array('nick_name'=>$field));
            if($info){
                return -1;
            }else{
                return 1;
            }
        }
    }

    //通过一对一关联获取用户信息
    public function getUser($id){
        $user = Yii::app()->db->createCommand()
            ->select('username,domain,is_domain, email,nick_name,sex,avatar_status,avatar_public,feeling,bg,intro,update_username')
            ->from('{{user}} u')
            ->leftJoin('{{user_extend}} p', 'u.id=p.uid')
            ->where('id=:id', array(':id'=>$id))
            ->queryRow();
        $user_extend = Yii::app()->db->createCommand()
            ->select('uid')
            ->from('{{user_extend}}')
            ->where('uid=:id', array(':id'=>$id))
            ->queryRow();
        if(!$user_extend){
           $ue_db = new UserExtend();
           $ue_db->uid = $id;
           $ue_db->save();
        }
        return $user;
    }
    //username
    public function getUser2($nick_name){
        $user = Yii::app()->db->createCommand()
            ->select('id,domain')
            ->from('{{user}}')
            ->where('nick_name=:nick_name', array(':nick_name'=>$nick_name))
            ->queryRow();
        return $user;
    }

    /**
     * @param $user_id 自己的id
     * @param $friend_id 对方的id
     * 加对方关注
     */
    public function getFollow($user_id,$friend_id){
        //我关注的人
        $follow_count = Relationship::model()->count('user_id=:user_id',array(':user_id'=>$user_id));  //+++
        //关注我的人
        //$followers_count = Relationship::model()->count('friend_id=:user_id',array(':user_id'=>$user_id));
        //他关注的
        //$follow_friend_count = Relationship::model()->count('user_id=:user_id',array(':user_id'=>$friend_id));
        //关注他的
        $followers_friend_count = Relationship::model()->count('friend_id=:user_id',array(':user_id'=>$friend_id));  //++
        $user_info = User::model()->findByPk($user_id);
        $user_info->total_follows = $follow_count;
        $user_info->update();
        $friend_info = User::model()->findByPk($friend_id);
        $friend_info->total_followers = $followers_friend_count;
        $friend_info->update();

    }
    /**
     * 通过$user_id 获取  基础用户信息
     * nick_name    domain    avatar_status   id     avatar_public
     */
    public function getBasicInfo($uid){
        $data = Yii::app()->db->createCommand()
            ->select('domain,nick_name,domain,avatar_status,id,avatar_public')
            ->from('{{user}}')
            ->where('id=:id', array(':id'=>$uid))
            ->queryRow();
        return $data;
    }

    /**
     * 通过$uid 获取 domain
     * @param $uid
     */
    public function getDomain($uid){
        $data = Yii::app()->db->createCommand()
            ->select('domain')
            ->from('{{user}}')
            ->where('id=:id', array(':id'=>$uid))
            ->queryRow();
        return $data['domain'];
    }



    //用户总喜欢数统计  写入用户表
    public function getFavorite($uid,$type='share'){
        $db = $this->findByPk($uid);
        if($type=='share'){
            $fs_count = FavoriteShare::model()->count('user_id=:user_id',array(':user_id'=>$uid));
            $db->total_favorite_share = $fs_count;
        }elseif($type=='album'){
            $fa_count = FavoriteAlbum::model()->count('user_id=:user_id',array(':user_id'=>$uid));
            $db->total_favorite_album = $fa_count;
        }
        $db->update();
    }

    //通过一对一修改用户资料
    public function updateUser($domain,$id,$username,$nick_name,$sex,$feeling,$extro){
        $uinfo = User::model()->findByPk($id);
        $uinfo->setScenario('update');
        if($uinfo->update_username ==0){  //表示没有修改过
            if($uinfo->username == $username || empty($username)){
                $data['update_username'] = 0;//没有修改
            }else{
                $uinfo->update_username = 1;
                $uinfo->username = CHtml::encode(Yii::app()->WordFilter->replacement($username));
                $data['username'] = CHtml::encode(Yii::app()->WordFilter->replacement($username));
                $data['update_username'] = 1;//修改了
            }

        }else{//修改过的
            $data['username'] = '';
            $data['update_username'] = 1;//修改了
        }
        if($uinfo->is_domain ==0){  //表示没有修改过
            if($uinfo->domain == $domain || empty($domain)){
                $data['is_domain'] = 0;//没有修改
            }else{
                $uinfo->is_domain = 1;
                $uinfo->domain = CHtml::encode(Yii::app()->WordFilter->replacement($domain));
                $data['domain'] = Yii::app()->params['webPath'].CHtml::encode(Yii::app()->WordFilter->replacement($domain));
                $data['is_domain'] = 1;//修改了
            }
        }else{//修改过的
            $data['domain'] = '';
            $data['is_domain'] = 1;//修改了
        }
        if($uinfo->nick_name != $nick_name && $nick_name){
            $uinfo->nick_name = CHtml::encode(Yii::app()->WordFilter->replacement($nick_name));
        }
        $uinfo->sex = $sex;
        $uinfo->feeling = CHtml::encode(Yii::app()->WordFilter->replacement($feeling));
        $ueinfo = UserExtend::model()->findByAttributes(array('uid'=>$id));
        $ueinfo->intro = CHtml::encode(Yii::app()->WordFilter->replacement($extro));
        $ueinfo->save();
        if($uinfo->save()){
            $data['status'] = 1;
            //修改auth
            $auth = Yii::app()->user->getState('user_auth');
            $auth['username'] = $uinfo->username;
            $auth['nick_name'] = $uinfo->nick_name;  //昵称
            $auth['feeling'] = $uinfo->feeling;
            Yii::app()->user->setState('user_auth',$auth);
        }else{
            $data['status'] = 0;
            $data['update_username'] = 0;
        }
        $data['nick_name'] = $uinfo->nick_name;
        echo CJSON::encode($data);
    }

    /**
     * 取得 粉丝排行榜
     */
    public function getFollowers($num){
        $user = Yii::app()->db->createCommand()
            ->select('id,domain,nick_name,total_followers,total_shares,avatar_status,avatar_public')
            ->from('{{user}} u')
            ->where('status=:status', array(':status'=>1))
            ->order('total_followers desc')
            ->limit($num)
            ->queryAll();
        foreach($user as $k=>$v){
            $user[$k]['info'] = Share::model()->getBasicUserShare($v['id'],4);
        }
        return $user;
    }

    /**
     * 取得发布排行榜
     * @param $num
     * @return mixed
     */
    public function getShares($num){
        $user = Yii::app()->db->createCommand()
            ->select('id,domain,nick_name,total_followers,total_shares,avatar_status,avatar_public')
            ->from('{{user}} u')
            ->where('status=:status', array(':status'=>1))
            ->order('total_shares desc')
            ->limit($num)
            ->queryAll();
        foreach($user as $k=>$v){
            $user[$k]['info'] = Share::model()->getBasicUserShare($v['id'],4);
        }
        return $user;
    }
    public function getStar($first,$total){
        $db = Yii::app()->db->createCommand();
        $db->select('u.id,u.nick_name,u.avatar_public,u.avatar_status,u.bg,u.domain');
        $db->from('{{user}} u');
        $db->where('u.status=:status',array(':status'=>1));
        $db->order('u.recommend desc,u.recommend_time desc,id desc');
        $db->limit($total,$first);
        $info = $db->queryAll();
        if($info){
            foreach($info as $k=>$v){
                //获取粉丝最新的3个图片
                $info[$k]['images'] = Share::model()->getThreeShare($v['id']);
            }
        }
        return $info;
    }
    public function recommendUser($uid){
        $info = $this->findByPk($uid);
        if($info){
            $info->recommend = 1;
            $info->recommend_time = time();
            $ok = $info->update();
            if($ok){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    public function getIndexInfo($uid){
        $db = Yii::app()->db->createCommand();
        $info = $db
            ->select('u.id,u.nick_name,u.domain,u.avatar_status,u.avatar_public,u.feeling,u.bg,u.total_followers,total_shares')
            ->from('{{user}} u')
            ->where('u.id=:id',array(':id'=>$uid))
            ->queryRow();
        return $info;
    }




}